package coreservlets.ch9;

import java.util.ArrayList;

public class ShoppingCart {
	private ArrayList<ItemOrder> itemsOrdered;
	
	public ShoppingCart() {
		this.itemsOrdered = new ArrayList<ItemOrder>();
	}
	
	public ArrayList<ItemOrder> getItemsOrdered() {
		return itemsOrdered;
	}
	
	public synchronized void addItem(String itemID){
		for (ItemOrder itemOrder : itemsOrdered) {
			if (itemOrder.getItemID().equals(itemID)) {
				itemOrder.incrementItems();
				return;
			}
		}
		ItemOrder order = new ItemOrder(Catalog.getItem(itemID));
		this.itemsOrdered.add(order);
	}
	
	public synchronized void setNumOrdered(String itemID, int numOrdered){
		ItemOrder order;
		for (int i = 0; i < itemsOrdered.size(); i++) {
			order = itemsOrdered.get(i);
			if (order.getItemID().equals(itemID)) {
				if (numOrdered <= 0) {
					itemsOrdered.remove(i);
				}else {
					order.setNumItems(numOrdered);
				}
				return;
			}
		}
		ItemOrder itemOrder = new ItemOrder(Catalog.getItem(itemID));
		this.itemsOrdered.add(itemOrder);
	}
}
